<?php

namespace app\index\controller;

use addons\thirdwork\library\Application;
use app\admin\model\PayslipFeedback;
use app\admin\model\PayslipLogs;
use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;

class Index extends Frontend
{
	protected $layout      = 'default';
	protected $noNeedRight = ['*'];
	protected $payslip_config;

	public function _initialize()
	{
		parent::_initialize();
		$auth = $this->auth;
		$this->assign('auth', $this->auth);

		$this->payslip_config = config('site.payslip_config');
		$this->assign('payslip_config', $this->payslip_config);
		$this->assign('is_mobile', $this->request->isMobile());

		$first = $this->request->param('first');
		if ($first == 'yes') {
			Session::delete('verification');
		}

		if (!Config::get('fastadmin.usercenter')) {
			$this->error(__('User center already closed'), '/');
		}

		//监听注册登录退出的事件
		Hook::add('user_login_successed', function ($user) use ($auth) {
			$expire = input('post.keeplogin') ? 30 * 86400 : 0;
			Cookie::set('uid', $user->id, $expire);
			Cookie::set('token', $auth->getToken(), $expire);
		});
		Hook::add('user_register_successed', function ($user) use ($auth) {
			Cookie::set('uid', $user->id);
			Cookie::set('token', $auth->getToken());
		});
		Hook::add('user_delete_successed', function ($user) use ($auth) {
			Cookie::delete('uid');
			Cookie::delete('token');
		});
		Hook::add('user_logout_successed', function ($user) use ($auth) {
			Cookie::delete('uid');
			Cookie::delete('token');
		});
	}

	protected function checkSession()
	{
		if ($this->payslip_config['open_query_pwd']) {
			$verification = Session::get('verification');
			if (empty($verification)) {
				$querypwd = $this->auth->querypwd;
				if ($querypwd) {
					$this->redirect('index/check_point');
				} else {
					$this->redirect('index/set_point');
				}
			}
		}
	}

	public function index()
	{
		$this->checkSession();
		$month = $this->request->get('month', '', 'trim');
		$year  = $this->request->get('year', '', 'trim');

		if (empty($month)) {
			$month = (new PayslipLogs)->where(['user_id' => $this->auth->id, 'status' => ['>', 0]])->order('month DESC')->value('month', date('Y-m'));
		}
		if (empty($year)) {
			$year = date('Y', strtotime($month));
		}

		$years       = [];
		$month_start = (new PayslipLogs)->where(['user_id' => $this->auth->id, 'status' => ['>', 0]])->order('month ASC')->value('month', date('Y-m'));
		$year_start  = date('Y', strtotime($month_start));
		for ($i = $year_start; $i >= $year; $i --) {
			$years[] = ['text' => $i];
		}

		$payslip_total = 0;

		$payslip_list = (new PayslipLogs)->alias('pl')
		                                 ->join('payslip p', 'p.id = pl.payslip_id', 'lEFT')
		                                 ->where(['pl.user_id' => $this->auth->id, 'pl.month' => $month, 'pl.status' => ['>', 0]])
		                                 ->field('pl.id, pl.payslip_total, pl.is_view, p.title')
		                                 ->select();

		if ($payslip_list) {
			foreach ($payslip_list as $item) {
				$payslip_total += $item['payslip_total'];
			}
		}

		$month_num     = 0;
		$max_money     = 0;
		$avg_money     = 0;
		$total_money   = 0;
		$payslip_total = number_format($payslip_total, 2);
		$year_chart    = [];
		for ($i = $year . '12'; $i >= $year . '01'; $i --) {
			$where        = [
				'user_id' => $this->auth->id,
				'month'   => date('Y-m', strtotime($i . '01')),
				'status'  => ['>', 0]
			];
			$money        = (new PayslipLogs)->where($where)->sum('payslip_total');
			$max_money    = max($max_money, $money);
			$month_num    += $money ? 1 : 0;
			$total_money  += $money;
			$year_chart[] = [
				'month' => date('m月', strtotime($i . '01')),
				'money' => $money
			];
		}

		if ($year_chart) {
			foreach ($year_chart as &$chart) {
				$chart['width'] = $max_money ? $chart['money'] / $max_money * 100 : 0;
				$chart['money'] = number_format($chart['money'], 2);
			}
			$avg_money = $month_num ? $total_money / $month_num : 0;
		}

		$data = [
			'month'         => $month, //列表月份
			'year'          => $year, //图表年份
			'year_chart'    => $year_chart, //年度工资图表
			'payslip_list'  => $payslip_list, //本月工资类型列表
			'payslip_total' => $payslip_total,
			'avg_money'     => number_format($avg_money, 2),
			'total_money'   => number_format($total_money, 2)
		];

		$this->assign($data);
		$this->assign('title', '工资条');
		$this->assign('back_btn', 'hide');
		$this->assignconfig('month', $month);
		$this->assignconfig('year', $year);
		$this->assignconfig('years', $years);
		return $this->view->fetch();
	}

	public function detail()
	{
		$this->checkSession();
		$month = $this->request->param('month', '', 'trim');
		if (empty($month)) {
			$this->error('参数错误');
		}
		$payslip_list  = (new PayslipLogs)->alias('pl')
		                                  ->join('payslip p', 'p.id = pl.payslip_id', 'lEFT')
		                                  ->where(['pl.user_id' => $this->auth->id, 'pl.month' => $month, 'pl.status' => ['>', 0]])
		                                  ->field('pl.*, p.title')
		                                  ->select();
		$time          = time();
		$can_confirm   = 0;
		$seconds       = 0;
		$payslip_total = 0;
		if ($payslip_list) {
			foreach ($payslip_list as &$item) {
				$item['payslip_json'] = json_decode($item['payslip_json'], TRUE);
				$payslip_total        += $item['payslip_total'];
				$seconds              = max($seconds, ($time - $item['createtime'])); //获取创建至今的秒数，取最大值
				if ($item['is_view'] == 0) { //只要有一个未确认，就显示可以确认
					$can_confirm = 1;
				}
			}
		}
		$feedback_seconds = $this->payslip_config['feedback_days'] * 86400; //有效的反馈时间秒
		$can_feedback     = $this->payslip_config['open_feedback'] && $feedback_seconds > $seconds; //开启反馈，并且在有效反馈时间内

		if ($this->request->isPost()) {
			PayslipLogs::update(['is_view' => 1], ['user_id' => $this->auth->id, 'month' => $month, 'status' => ['>', 0]]);
			$this->success('已确认');
		}

		$data = [
			'month'         => $month,
			'payslip_type'  => array2select(config('site.payslip_type')),
			'payslip_list'  => $payslip_list,
			'payslip_total' => number_format($payslip_total, 2),
			'can_confirm'   => $can_confirm,
			'can_feedback'  => $can_feedback
		];

		$this->assign($data);
		$this->assign('title', '工资条详情');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function feedback()
	{
		$this->checkSession();
		$month = $this->request->param('month', '', 'trim,strip_tags,htmlspecialchars');
		if (empty($month)) {
			$this->error('参数错误');
		}
		if ($this->request->isPost()) {
			$content = $this->request->post('content', '', 'trim,strip_tags,htmlspecialchars');
			if (empty($month)) {
				$this->error('参数错误');
			}
			if (empty($content)) {
				$this->error('请输入您的反馈问题');
			}
			$row = (new PayslipFeedback)->where(['user_id' => $this->auth->id, 'month' => $month])->find();
			if ($row) {
				$row->content_json = PayslipFeedback::feedback_log($row['content_json'], $content);
				$row->status       = 1;
				$row->save();
			} else {
				$data = [
					'user_id'      => $this->auth->id,
					'month'        => $month,
					'content_json' => PayslipFeedback::feedback_log([], $content),
					'status'       => 1
				];
				PayslipFeedback::create($data);
			}
			PayslipLogs::update(['is_feedback' => 1], ['user_id' => $this->auth->id, 'month' => $month]);

			$touser = $this->get_manage_users();
			$work   = new Application(get_addon_config('thirdwork'));
			$work->wechatwork->sendTextMessage('有同事给你发了反馈信息，请进入后台查看', $touser);

			$this->success('反馈成功，请耐心等待回复');
		}

		$content_json = (new PayslipFeedback)->where(['user_id' => $this->auth->id, 'month' => $month])->value('content_json');
		$content_logs = $content_json ? json_decode($content_json, TRUE) : [];

		$this->assign('month', $month);
		$this->assign('content_logs', $content_logs);
		$this->assign('title', '反馈处理结果');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function my()
	{
		$this->checkSession();
		$this->assign('title', '我的');
		$this->assign('back_btn', 'hide');
		return $this->view->fetch();
	}

	public function my_feedback()
	{
		$this->checkSession();
		$list = (new PayslipFeedback)->where(['user_id' => $this->auth->id])->order('month DESC')->select();
		if ($list) {
			foreach ($list as &$item) {
				$item['content'] = json_decode($item['content_json'], TRUE);
			}
		}
		$this->assign('list', $list);
		$this->assign('title', '我的反馈');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function my_activation()
	{
		$this->checkSession();
		$this->assign('title', '激活码');
		$this->assign('back_btn', 'hide');
		return $this->view->fetch();
	}

	public function my_payslip()
	{
		$this->checkSession();
		$list   = [];
		$months = (new PayslipLogs)->where(['user_id' => $this->auth->id, 'status' => ['>', 0]])->group('month')->order('month DESC')->column('month');
		if ($months) {
			foreach ($months as $month) {
				$payslip_list = (new PayslipLogs)->where(['user_id' => $this->auth->id, 'month' => $month, 'status' => ['>', 0]])
				                                 ->field('id, payslip_type, payslip_json, payslip_total, month')
				                                 ->order('month DESC')
				                                 ->select();
				if ($payslip_list) {
					foreach ($payslip_list as $key => $value) {
						$payslip_list[$key]['payslip_json'] = json_decode($value['payslip_json'], TRUE);
					}
					$list[] = [
						'month' => $month,
						'list'  => $payslip_list
					];
				}
			}
		}
		$data = [
			'list'         => $list,
			'payslip_type' => array2select(config('site.payslip_type'))
		];
		$this->assign($data);
		$this->assign('title', '工资条历史');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function my_repassword()
	{
		$this->checkSession();
		$this->assign('title', '设置手势密码');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function check_point()
	{
		$verification = Session::get('verification');
		if ($verification) {
			if ($this->request->isPost()) {
				$this->success('验证成功');
			} else {
				$this->redirect('index/index');
			}
		}
		if ($this->request->isPost()) {
			$point = $this->request->post('point');
			if ($point == $this->auth->querypwd) {
				Session::set('verification', 1);
				$this->success('身份识别成功');
			} else {
				$this->error('身份识别码错误，请重新输入');
			}
		}
		$this->assign('title', '手势密码验证');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function set_point()
	{
		$this->assign('title', '设置手势密码');
		$this->assign('back_btn', 'back');
		return $this->view->fetch();
	}

	public function save_point()
	{
		if ($this->request->isPost()) {
			$old_point = $this->request->post('old_point');
			$new_point = $this->request->post('new_point');
			if (empty($new_point)) {
				$this->error('不正确的格式，请重新输入');
			}
			if ($this->auth->querypwd && $this->auth->querypwd != $old_point) {
				// $this->error('原身份识别码输入错误');
			}
			\app\common\model\User::update(['querypwd' => $new_point], ['id' => $this->auth->id]);
			$this->success('解锁图案绘制设置成功', 'index/index');
		}
	}

	public function reset_pwd()
	{
		$formuser = (new \app\common\model\User)->alias('u')
		                                        ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
		                                        ->where(['u.id' => $this->auth->id])
		                                        ->field('u.id, u.nickname, ud.name AS `department_name`')
		                                        ->find();
		$touser   = (new \app\common\model\User)->where(['group_id' => 2])->column('username');
		if (empty($touser)) {
			$this->error('系统未设置审核人员，请联系管理员');
		}
		$touser = $this->get_manage_users();
		$app    = new Application(get_addon_config('thirdwork'));
		$app->wechatwork->sendCardMessage($formuser, $touser);
		$this->success('已发送请求，请耐心等待审核');
	}

	protected function get_manage_users()
	{
		$touser   = (new \app\common\model\User)->where(['group_id' => 2])->column('username');
		if (empty($touser)) {
			$this->error('系统未设置审核人员，请联系管理员');
		}
		return implode('|', $touser);
	}

}
